package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.StudentService;
import so.ifl.vo.StudentVo;

/**
 *create by aaron.lu
 *create at 2013-7-25 下午9:26:00
 *<mailto: atyuan.lu@gmail.com>
 **/
public class ApplyFormBlankPrinter implements Iprinter {
	
	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	private String LIST_ = "list";
	
	@Override
	public void print(Map<String, Object> data, HttpServletResponse response, HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		List<StudentVo> list = (List<StudentVo>)data.get(LIST_);
 		
		
		if (null != list && list.size() > 0) {
			StudentVo studentVo = list.get(0);
			
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();// 用于存储每页生成PDF流
			String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
			String model_path = servletPath + "/templates/apply_form_blank.pdf";
			PdfReader reader = new PdfReader(model_path);
			BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			
			PdfStamper pdfStamper = new PdfStamper(reader, baos);			
			AcroFields form = pdfStamper.getAcroFields(); 
			form.addSubstitutionFont(baseFontChinese);
			
			form.setField("studentName", studentVo.getStudentName());
			form.setField("officeName", studentVo.getOfficeName());
			form.setField("studentDriveNowNumber", studentVo.getStudentDriveNowNumber());
			String studentSex = null != studentVo.getStudentSex() && studentVo.getStudentSex().intValue() == 1 ? "男":"女";
			form.setField("studentSex", studentSex);
			form.setField("studentBirthday", null == studentVo.getStudentBirthday()? "":DateUtil.YMD_SDF_POINT.format(studentVo.getStudentBirthday()));
			
			boolean should_print_temp = false;
			
			if(StringHelper.isNotEmpty(studentVo.getStudentCertificateType())){
				if (studentVo.getStudentCertificateType().equals("sl")) {
					form.setField("studentCertificateType", "居民身份证");
					form.setField("studentCertificateType2", "流动人员登记表");
					should_print_temp = true;//有流表，则需要打印
				}else if(studentVo.getStudentCertificateType().equals("sj")){
					form.setField("studentCertificateType", "居民身份证");
					form.setField("studentCertificateType2", "居住证");  
					should_print_temp = true;//有居住证，则需要打印
				}else{
					form.setField("studentCertificateType", studentVo.getStudentCertificateType());
				}				
			}
			
			String studentTemporaryResidentialPermit = studentVo.getStudentTemporaryResidentialPermit(); 
			if (StringHelper.isNotEmpty(studentTemporaryResidentialPermit) && should_print_temp) {//拥有居住证
				for (int i = 0; i < 18; i++) {
					if (studentTemporaryResidentialPermit.length() > i) {
						form.setField("s" + i, studentTemporaryResidentialPermit.substring(i, i + 1));
					}				
				}
			}else{//如果没有居住证
				//do nothing 没有居住证就什么都不显示
			}
			
			
			String studentCertificateNumber = studentVo.getStudentCertificateNumber();
			for (int i = 0; i < 18; i++) {
				if (studentCertificateNumber.length() > i) {
					form.setField("n" + i, studentCertificateNumber.substring(i, i + 1));
				}				
			}
			form.setField("studentAddress", studentVo.getStudentContactAddress());
			form.setField("studentPhone", studentVo.getStudentPhone());
			form.setField("studentTel", studentVo.getStudentTel());
			form.setField("studentEmail", studentVo.getStudentEmail());
			form.setField("studentNationality", studentVo.getStudentNationality());
			form.setField("studentZip", studentVo.getStudentZip());
			form.setField("studentApplyDriveType", studentVo.getStudentApplyDriveType());		
			form.setField("studentDriveTypeNow", studentVo.getStudentDriveTypeNow());
			
			if (null != studentVo.getStudentApplyType() && studentVo.getStudentApplyType().equals("初学")) {
				form.setField("studentApplyType1", "√");
			}else{
				form.setField("studentApplyType2", "√");
			}
			
			
			
			
			
			
			
			pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
			pdfStamper.close();
			
			ServletOutputStream out = response.getOutputStream();			
			response.setContentType("application/pdf");
			
			baos.writeTo(out);
			out.flush();						
			
			baos.close();
		}		
	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)throws Exception {
		String studentId = request.getParameter("studentId");
		Map<String, Object> result = new HashMap<String, Object>();
		
		if (StringHelper.isNotEmpty(studentId)) {
		
			
			ServletContext servletContext = request.getSession().getServletContext();		
			ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			
			StudentService studentService = (StudentService)appctx.getBean("studentService");
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("student_id_", studentId);
 			
			List<StudentVo> list = studentService.queryStudentWithParamAndPagination(params, 0, 1);
			
			result.put(LIST_, list);
		}		

		return result;
	}

}
